﻿using NewWms.ViewModels;
using NewWms.ViewModels.DialogsModel;
using NewWms.Views;
using NewWms.Views.Dialogs;
using Prism.DryIoc;
using Prism.Ioc;
using Prism.Services.Dialogs;
using System.Windows;
using wms_wpf;
using wms_wpf.ViewModels;
using wms_wpf.Views;
using MessageBox = System.Windows.MessageBox;
using Reconstruct_Desktop.Views.Dialogs;
using Reconstruct_Desktop.ViewModels.DialogsModel;
using Reconstruct_Desktop.Views;
using Reconstruct_Desktop.ViewModels;
using Reconstruct_Desktop.Views.OrderManage;
using Reconstruct_Desktop.ViewModels.OrderManageViewModel;
using Reconstruct_Desktop.ViewModels.MaterialRackManageViewModel;
using Reconstruct_Desktop.Views.OrderManageView;
using Quartz.Impl;
using Quartz;
using static Quartz.Logging.OperationName;
using Reconstruct_Desktop.Views.ManualOperateView;
using Reconstruct_Desktop.ViewModels.ManualOperateViewModel;
using Reconstruct_Desktop.Views.UserMangerView;
using Reconstruct_Desktop.ViewModels.UserManageViewModel;
using AutoUpdaterDotNET;

namespace NewWms
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : PrismApplication
    {
        protected override Window CreateShell()
        {
            return Container.Resolve<MainWindow>();
        }
        private static System.Threading.Mutex mutex;
        private void AutoUpdaterOnCheckForUpdateEvent(UpdateInfoEventArgs args)
        {
            if (args != null && args.IsUpdateAvailable)
            {
                // 自动下载并安装
                AutoUpdater.DownloadUpdate(args);
                // 如果需要静默安装，可以在这里处理
            }
        }
        protected override void OnStartup(StartupEventArgs e)
        {
            AutoUpdater.CheckForUpdateEvent += AutoUpdaterOnCheckForUpdateEvent;
            AutoUpdater.Start("http://192.168.31.12:1888/Updates/update.xml");
            
          
         
            mutex = new System.Threading.Mutex(true, "WcsZz");
            if (mutex.WaitOne(0, false))
            {
                RegisterEvents();
                base.OnStartup(e);
            }
            else
            {
                MessageBox.Show("程序已经在运行！", "提示");
                this.Shutdown();
            }
        }
        //异常处理
        private void RegisterEvents()
        {
            //Task线程内未捕获异常处理事件
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;//Task异常 

            //UI线程未捕获异常处理事件（UI主线程）
            this.DispatcherUnhandledException += App_DispatcherUnhandledException;

            //非UI线程未捕获异常处理事件(例如自己创建的一个子线程)
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

        }
        //task exception
        private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {

            try
            {
                var exception = e.Exception as Exception;
                if (exception != null)
                {
                    HandleException(exception);
                }
            }
            catch (Exception ex) 
            {
                HandleException(ex);
            }
            finally
            {
                e.SetObserved();
            }

        }

        //非UI线程未捕获异常处理事件(例如自己创建的一个子线程)  
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                var exception = e.ExceptionObject as Exception;
                if (exception != null)
                {
                    HandleException(exception);
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
         
        }
        //UI线程未捕获异常处理事件（UI主线程
        private static void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            try
            {
                HandleException(e.Exception);
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
            finally
            {
                e.Handled = true;
            }
        }
        private static void HandleException(Exception ex)
        {
            LognetHelper.WriteLog("异常捕获+：", ex);
            //MessageBox.Show(ex.Message+"\r\n"+ex.StackTrace);
        }




        protected async override void OnInitialized()
        {

            var dialog = Container.Resolve<IDialogService>();
            dialog.ShowDialog("LoginView", callback =>
            {
                if (callback.Result == ButtonResult.None)
                {
                    Application.Current.Shutdown();
                    return;
                }
                if (callback.Result != ButtonResult.OK)
                {
                    return;
                }

            });


            base.OnInitialized();
        }
        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterForNavigation<MainWindow, MainWindowModel>();//注册view和viewmodel
            containerRegistry.RegisterForNavigation<MaterialView, MaterialViewModel>("MaterialView");
            containerRegistry.RegisterForNavigation<BoxConfigView, BoxConfigViewModel>("BoxConfigView");
            containerRegistry.RegisterForNavigation<UpAndDownShelvesView, UpAndDownShelvesViewModel>("UpAndDownShelvesView");
            containerRegistry.RegisterForNavigation<BoxShelfView, BoxShelfViewModel>("BoxShelfView");
            containerRegistry.RegisterForNavigation<WarehouseConfigView, WarehouseConfigViewModel>("WarehouseConfigView");
            containerRegistry.RegisterForNavigation<ShelfManageView, ShelfManageViewModel>("ShelfManageView");
            containerRegistry.RegisterForNavigation<InventorydetailsView, InventorydetailsViewModel>("InventorydetailsView");
            containerRegistry.RegisterForNavigation<RecordView, RecordViewViewModel>("RecordView");
            containerRegistry.RegisterForNavigation<LogNoteView, LogNoteViewModel>("LogNoteView");
            containerRegistry.RegisterForNavigation<MaterialBaseView, MaterialBaseViewMode>("MaterialBaseView");
            containerRegistry.RegisterForNavigation<EntranceRegionView, EntranceRegionViewModel>("EntranceRegionView");
            containerRegistry.RegisterForNavigation<PutInOrderManageView, PutInOrderManageViewModel>("PutInOrderManageView");
            containerRegistry.RegisterForNavigation<PutOutOrderManageView, PutOutOrderManageViewModel>("PutOutOrderManageView");
            containerRegistry.RegisterForNavigation<PollingView, PollingViewModel>("PollingView");
            containerRegistry.RegisterForNavigation<EmptyBoxView, EmptyBoxViewModel>("EmptyBoxView");
            containerRegistry.RegisterForNavigation<UserInfoView, UserInfoViewModel>("UserInfoView");


            containerRegistry.RegisterDialog<CreateBoxsDialog, CreateBoxsDialogModel>("CreateBoxsDialog");
            containerRegistry.RegisterDialog<CreateWarehouseDialog, CreateWarehouseDialogModel>("CreateWarehouseDialog");
            containerRegistry.RegisterDialog<LoginView, LoginViewModel>();
            containerRegistry.RegisterDialog<UpdateBoxDialog, UpdateBoxDialogModel>("UpdateBoxDialog");
            containerRegistry.RegisterDialog<CreateMaterialPropertyDialog, CreateMaterialPropertyDialogModel>("CreateMaterialPropertyDialog");
            containerRegistry.RegisterDialog<UpdateWarehouseLineDialog, UpdateWarehouseLineDialogModel>("UpdateWarehouseLineDialog");
            containerRegistry.RegisterDialog<CreateInlethouseLineDialog, CreateInlethouseLineDialogModel>("CreateInlethouseLineDialog");
            containerRegistry.RegisterDialog<UpdateInlethouseLineDialog,UpdateInlethouseLineDialogModel>("UpdateInlethouseLineDialog");
            containerRegistry.RegisterDialog<Create_BintypeDialog, Create_BintypeDialogModel>("Create_BintypeDialog");
            containerRegistry.RegisterDialog<StockTakingDialog, StockTakingDialogModel>("StockTakingDialog");
        }
    }

}
